package com.example.springboot.controller;

import com.example.springboot.entity.UserInfo;
import com.example.springboot.model.ApiResponse;
import com.example.springboot.service.UserService;
<<<<<<< HEAD
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
=======
import com.example.springboot.utils.AliOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
>>>>>>> 73359ff (更新头像)

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
<<<<<<< HEAD
=======
import java.util.UUID;
>>>>>>> 73359ff (更新头像)

/**
 * 登录控制器
 * 处理用户登录相关的HTTP请求，提供登录验证功能
 * 接收前端发送的登录请求，调用服务层进行用户验证，并返回统一格式的响应
 */
@RestController
@RequestMapping("/api")
public class LoginController {

    /**
     * 注入用户服务接口
     * 用于调用用户登录验证等业务逻辑
     */
    @Autowired
    private UserService userService;

    /**
     * 用户登录接口
     * 接收用户账号和密码，验证用户身份，并返回登录结果
     * 
     * @param loginRequest 登录请求参数，包含userAccount(用户账号)和userPassword(用户密码)
     * @return 登录结果，成功返回用户信息，失败返回错误信息
     */
    @PostMapping("/login")
    public ResponseEntity<ApiResponse> login(@RequestBody Map<String, Object> loginRequest) {
        System.out.println("Received login request: " + loginRequest);
        try {
            // 参数校验
            if (!loginRequest.containsKey("userAccount") ||
                    !loginRequest.containsKey("userPassword")) {
                return ResponseEntity.ok(ApiResponse.error("账号和密码不能为空"));
            }

            Integer userAccount = Integer.valueOf(loginRequest.get("userAccount").toString());
            Integer userPassword = Integer.valueOf(loginRequest.get("userPassword").toString());

            // 调用服务层验证用户
            UserInfo userInfo = userService.login(userAccount.longValue(), userPassword.longValue());

            if (userInfo != null) {
                // 登录成功，返回用户信息（可以考虑不返回密码等敏感信息）
                return ResponseEntity.ok(ApiResponse.success("登录成功", userInfo));
            } else {
                // 登录失败
                return ResponseEntity.ok(ApiResponse.error("账号或密码错误"));
            }
        } catch (NumberFormatException e) {
            // 处理数字格式异常
            return ResponseEntity.ok(ApiResponse.error("账号或密码格式错误"));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.ok(ApiResponse.error("登录失败: " + e.getMessage()));
        }
    }

    /**
     * 用户注册接口
     * 接收用户注册信息，创建新用户，并返回注册结果
     * 
<<<<<<< HEAD
     * @param registerRequest 注册请求参数，包含用户账号、密码和个人信息等
     * @return 注册结果，成功返回用户信息，失败返回错误信息
     */
    @PostMapping("/register")
    public ResponseEntity<ApiResponse> register(@RequestBody Map<String, Object> registerRequest) {
        System.out.println("Received register request: " + registerRequest);
        try {
            // 参数校验
            if (!registerRequest.containsKey("userAccount") ||
                    !registerRequest.containsKey("userPassword") ||
                    !registerRequest.containsKey("userName") ||
                    !registerRequest.containsKey("userSex") ||
                    !registerRequest.containsKey("userBirthday") ||
                    !registerRequest.containsKey("userAge") ||
                    !registerRequest.containsKey("userType")) {
                return ResponseEntity.ok(ApiResponse.error("注册信息不完整"));
            }

            // 获取注册参数
            Integer userAccount = Integer.valueOf(registerRequest.get("userAccount").toString());
            Integer userPassword = Integer.valueOf(registerRequest.get("userPassword").toString());
            String userName = registerRequest.get("userName").toString();
            String userSex = registerRequest.get("userSex").toString();
            String phoneNumber = registerRequest.containsKey("phoneNumber")
                    ? registerRequest.get("phoneNumber").toString()
                    : null;
=======
     * @param userBirthdayStr 注册请求参数，包含用户账号、密码和个人信息等
     * @return 注册结果，成功返回用户信息，失败返回错误信息
     */
    @PostMapping("/register")
    public ResponseEntity<ApiResponse> register(
            @RequestParam("userAccount") Long userAccount,
            @RequestParam("userPassword") Long userPassword,
            @RequestParam("userName") String userName,
            @RequestParam("userSex") String userSex,
            @RequestParam("userBirthday") String userBirthdayStr,
            @RequestParam("userAge") Integer userAge,
            @RequestParam("userType") String userType,
            @RequestParam(value = "phoneNumber", required = false) String phoneNumber,
            @RequestParam(value = "userBirthPlace", required = false) String userBirthPlace,
            @RequestParam(value = "userLivePlace", required = false) String userLivePlace,
            @RequestParam(value = "avatar", required = false) MultipartFile avatarFile) { // 新增头像参数

        try {
            // 检查账号是否已存在
            if (userService.isAccountExists(userAccount)) {
                return ResponseEntity.ok(ApiResponse.error("账号已存在"));
            }
>>>>>>> 73359ff (更新头像)

            // 处理日期格式
            Date userBirthday;
            try {
<<<<<<< HEAD
                String birthdayStr = registerRequest.get("userBirthday").toString();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                userBirthday = dateFormat.parse(birthdayStr);
=======
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                userBirthday = dateFormat.parse(userBirthdayStr);
>>>>>>> 73359ff (更新头像)
            } catch (ParseException e) {
                return ResponseEntity.ok(ApiResponse.error("生日格式错误"));
            }

<<<<<<< HEAD
            Integer userAge = Integer.valueOf(registerRequest.get("userAge").toString());
            String userBirthPlace = registerRequest.containsKey("userBirthPlace")
                    ? registerRequest.get("userBirthPlace").toString()
                    : null;
            String userLivePlace = registerRequest.containsKey("userLivePlace")
                    ? registerRequest.get("userLivePlace").toString()
                    : null;
            String userType = registerRequest.get("userType").toString();

            // 检查账号是否已存在
            if (userService.isAccountExists(userAccount.longValue())) {
                return ResponseEntity.ok(ApiResponse.error("账号已存在"));
            }

            // 创建用户对象
            UserInfo userInfo = new UserInfo();
            userInfo.setUserAccount(userAccount.longValue());
            userInfo.setUserPassword(userPassword.longValue());
=======
            // 创建用户对象
            UserInfo userInfo = new UserInfo();
            userInfo.setUserAccount(userAccount);
            userInfo.setUserPassword(userPassword);
>>>>>>> 73359ff (更新头像)
            userInfo.setUserName(userName);
            userInfo.setUserSex(userSex);
            userInfo.setPhoneNumber(phoneNumber);
            userInfo.setUserBirthday(userBirthday);
            userInfo.setUserAge(userAge);
            userInfo.setUserBirthPlace(userBirthPlace);
            userInfo.setUserLivePlace(userLivePlace);
            userInfo.setUserType(userType);

<<<<<<< HEAD
=======
            // 处理头像上传
            if (avatarFile != null && !avatarFile.isEmpty()) {
                String originalFilename = avatarFile.getOriginalFilename();
                String fileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
                String avatarUrl = AliOssUtil.uploadFile(fileName, avatarFile.getInputStream());
                userInfo.setUserAvatar(avatarUrl); // 设置头像URL
            }

>>>>>>> 73359ff (更新头像)
            // 调用服务层进行注册
            UserInfo registeredUser = userService.register(userInfo);

            if (registeredUser != null) {
<<<<<<< HEAD
                // 注册成功
                return ResponseEntity.ok(ApiResponse.success("注册成功", registeredUser));
            } else {
                // 注册失败
                return ResponseEntity.ok(ApiResponse.error("注册失败"));
            }

        } catch (NumberFormatException e) {
            return ResponseEntity.ok(ApiResponse.error("账号或密码格式错误"));
=======
                return ResponseEntity.ok(ApiResponse.success("注册成功", registeredUser));
            } else {
                return ResponseEntity.ok(ApiResponse.error("注册失败"));
            }
        } catch (NumberFormatException e) {
            return ResponseEntity.ok(ApiResponse.error("参数格式错误"));
>>>>>>> 73359ff (更新头像)
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.ok(ApiResponse.error("注册失败: " + e.getMessage()));
        }
    }

    /**
     * 用户信息更新接口
     * 接收用户更新信息，更新用户数据，并返回更新结果
     * 
     * @param updateRequest 更新请求参数，包含用户ID和需要更新的信息
     * @return 更新结果，成功返回更新后的用户信息，失败返回错误信息
     */
<<<<<<< HEAD
=======

>>>>>>> 73359ff (更新头像)
    @PostMapping("/user/update")
    public ResponseEntity<ApiResponse> updateUserInfo(@RequestBody Map<String, Object> updateRequest) {
        System.out.println("Received user update request: " + updateRequest);
        try {
            // 参数校验
            if (!updateRequest.containsKey("userId")) {
                return ResponseEntity.ok(ApiResponse.error("用户ID不能为空"));
            }

            Integer userId = Integer.valueOf(updateRequest.get("userId").toString());

            // 查找现有用户
            UserInfo existingUser = userService.findUserById(userId);
            if (existingUser == null) {
                return ResponseEntity.ok(ApiResponse.error("用户不存在"));
            }

            // 更新用户信息
            if (updateRequest.containsKey("userName")) {
                existingUser.setUserName(updateRequest.get("userName").toString());
            }

            if (updateRequest.containsKey("userSex")) {
                existingUser.setUserSex(updateRequest.get("userSex").toString());
            }

            if (updateRequest.containsKey("phoneNumber")) {
                existingUser.setPhoneNumber(updateRequest.get("phoneNumber").toString());
            }

            if (updateRequest.containsKey("userBirthday")) {
                try {
                    String birthdayStr = updateRequest.get("userBirthday").toString();
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    Date userBirthday = dateFormat.parse(birthdayStr);
                    existingUser.setUserBirthday(userBirthday);
                } catch (ParseException e) {
                    return ResponseEntity.ok(ApiResponse.error("生日格式错误"));
                }
            }

            if (updateRequest.containsKey("userAge")) {
                existingUser.setUserAge(Integer.valueOf(updateRequest.get("userAge").toString()));
            }

            if (updateRequest.containsKey("userBirthPlace")) {
                existingUser.setUserBirthPlace(updateRequest.get("userBirthPlace").toString());
            }

            if (updateRequest.containsKey("userLivePlace")) {
                existingUser.setUserLivePlace(updateRequest.get("userLivePlace").toString());
            }

            if (updateRequest.containsKey("userType")) {
                existingUser.setUserType(updateRequest.get("userType").toString());
            }

            // 调用服务层进行更新
            UserInfo updatedUser = userService.updateUserInfo(existingUser);

            if (updatedUser != null) {
                // 更新成功
                return ResponseEntity.ok(ApiResponse.success("用户信息更新成功", updatedUser));
            } else {
                // 更新失败
                return ResponseEntity.ok(ApiResponse.error("用户信息更新失败"));
            }

<<<<<<< HEAD
=======

>>>>>>> 73359ff (更新头像)
        } catch (NumberFormatException e) {
            return ResponseEntity.ok(ApiResponse.error("用户ID格式错误"));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.ok(ApiResponse.error("更新失败: " + e.getMessage()));
        }
    }
<<<<<<< HEAD
=======

    /**
     * 用户头像更新接口
     * 接收用户ID和上传的头像文件，更新用户头像，并返回更新结果
     *
     * @param userId 用户ID
     * @param file 上传的头像文件
     * @return 更新结果，成功返回更新后的用户信息，失败返回错误信息
     */
    @PostMapping("/user/update/avatar")
    public ResponseEntity<ApiResponse> updateUserAvatar(
            @RequestParam("userId") Integer userId,
            @RequestParam("file") MultipartFile file) {
        try {
            UserInfo existingUser = userService.findUserById(userId);
            if (existingUser == null) {
                return ResponseEntity.ok(ApiResponse.error("用户不存在"));
            }

            // 使用 AliOssUtil 上传文件并获取真实 URL
            String originalFilename = file.getOriginalFilename();
            String fileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
            String avatarUrl = AliOssUtil.uploadFile(fileName, file.getInputStream());

            // 更新用户头像字段
            existingUser.setUserAvatar(avatarUrl);

            // 保存到数据库
            UserInfo updatedUser = userService.updateUserInfo(existingUser);

            return ResponseEntity.ok(ApiResponse.success("头像更新成功", updatedUser));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.ok(ApiResponse.error("更新失败: " + e.getMessage()));
        }
    }
>>>>>>> 73359ff (更新头像)
}